package client

import (
	"context"
	"google.golang.org/grpc"
	keep "keep/common/proto"
)

type Handler func(ctc context.Context, in keep.KeepClient) (interface{}, error)

func KeepClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8888", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := keep.NewKeepClient(dial)

	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	defer dial.Close()
	return res, nil
}

func ClassInfo(ctx context.Context, i *keep.KeepReservationInfoReq) (*keep.KeepReservationInfoResp, error) {
	client, err := KeepClient(ctx, func(ctc context.Context, in keep.KeepClient) (interface{}, error) {
		info, err := in.KeepReservationInfo(ctx, i)
		if err != nil {
			return nil, err
		}
		return info, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*keep.KeepReservationInfoResp), nil
}
func ClassReservation(ctx context.Context, i *keep.KeepReservationReq) (*keep.KeepReservationResp, error) {
	client, err := KeepClient(ctx, func(ctc context.Context, in keep.KeepClient) (interface{}, error) {
		info, err := in.KeepReservation(ctx, i)
		if err != nil {
			return nil, err
		}
		return info, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*keep.KeepReservationResp), nil
}
func ReservationConfirm(ctx context.Context, i *keep.ReservationConfirmReq) (*keep.ReservationConfirmResp, error) {
	client, err := KeepClient(ctx, func(ctc context.Context, in keep.KeepClient) (interface{}, error) {
		info, err := in.ReservationConfirm(ctx, i)
		if err != nil {
			return nil, err
		}
		return info, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*keep.ReservationConfirmResp), nil
}
func MyReservation(ctx context.Context, i *keep.MyReservationInfoReq) (*keep.MyReservationInfoResp, error) {
	client, err := KeepClient(ctx, func(ctc context.Context, in keep.KeepClient) (interface{}, error) {
		info, err := in.MyReservation(ctx, i)
		if err != nil {
			return nil, err
		}
		return info, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*keep.MyReservationInfoResp), nil
}

func RemindUser(ctx context.Context, i *keep.RemindUserReq) (*keep.RemindUserResp, error) {
	client, err := KeepClient(ctx, func(ctc context.Context, in keep.KeepClient) (interface{}, error) {
		info, err := in.RemindUser(ctx, i)
		if err != nil {
			return nil, err
		}
		return info, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*keep.RemindUserResp), nil
}
func DelReservation(ctx context.Context, i *keep.DelReservationReq) (*keep.DelReservationResp, error) {
	client, err := KeepClient(ctx, func(ctc context.Context, in keep.KeepClient) (interface{}, error) {
		info, err := in.DelReservation(ctx, i)
		if err != nil {
			return nil, err
		}
		return info, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*keep.DelReservationResp), nil
}
